package com.ydy.netty.service.impl;

import com.ydy.common.constant.Constant;
import com.ydy.common.model.ChatRecord;
import com.ydy.common.model.User;
import com.ydy.common.model.UserFriend;
import com.ydy.common.util.CodeUtil;
import com.ydy.common.util.DateUtil;
import com.ydy.common.util.RedisUtil;
import com.ydy.common.vo.UserFriendVo;
import com.ydy.netty.mapper.NettyMapper;
import com.ydy.netty.service.NettyService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;

@Service
public class NettyServiceImpl implements NettyService {

    @Autowired
    private NettyMapper nettyMapper;

    @Autowired
    private RedisTemplate<Serializable, Object> redisTemplate;


    @Override
    public List<UserFriendVo> getUserFriendsList(String userCode) {
        List<UserFriendVo> list = nettyMapper.getUserFriendsList(userCode);
        //获得群聊记录
        List<UserFriendVo> groupList = nettyMapper.getUserGroupList(userCode);
        list.addAll(groupList);
        //排序  按时间
        Collections.sort(list);
        list.forEach(v ->{
            v.setShowTime(exchangeMessageTime(v.getMessageTime(),false));
        });
        return list;
    }

    /**
     * 聊天时间的显示转换
     * @Title: exchangeMessageTime
     * @author: dy.yin 2021/4/30 14:52
     * @param: [messageTime 信息时间，isAppend 是否拼接时分]
     * @return: java.lang.String
     * @throws
     */
    private String exchangeMessageTime(Timestamp messageTime,boolean isAppend) {
        String returnTime = "";
        //当前时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        //当前时间的年/月/日
        String currentYmd = DateUtil.dateFormat(timestamp,DateUtil.DATE_FORMAT_LINEYYYYMMDD);
        if(messageTime == null ){return "";}
        //聊天时间转换
        String msgYmd = DateUtil.timestampFormat(messageTime,DateUtil.DATE_FORMAT_LINEYYYYMMDD);

        //时分
        String hm = DateUtil.timestampFormat(messageTime,DateUtil.DATE_FORMAT_HHMI);
        //计算是否今天
        if(currentYmd.equals(msgYmd)){
            returnTime = hm;
        }else{
            //不是今天  计算相差几天
            int count = DateUtil.differentDays(messageTime,timestamp);
            if(count > 5 ){
                if(isAppend) {
                    returnTime = DateUtil.timestampFormat(messageTime, DateUtil.DATE_TIME_FORMAT_YYYY年MM月DD日)
                            + "    ";
                }else{
                    returnTime = msgYmd;
                }
            }else{
                if(count == 1){
                    returnTime = "昨天  ";
                }else{
                    returnTime = DateUtil.getDayWeek(messageTime);
                }
            }
            //是否拼接时间
            if(isAppend){
                returnTime += hm;
            }

        }
        return returnTime;
    }

    @Override
    public void addFriend(String userCode,String friendCode) {
        UserFriend userFriend = new UserFriend(userCode,friendCode,0,CodeUtil.getCode());
        nettyMapper.addFriend(userFriend);
    }

    @Override
    public List<UserFriendVo> getCanAddFriendList(String userCode) {
        return nettyMapper.getCanAddFriendList(userCode);
    }

    @Override
    public void insertChatRecord(ChatRecord chatRecord) {
        nettyMapper.insertChatRecord(chatRecord);
    }

    @Override
    public Map<String, List<ChatRecord>> queryChatRecord(String userCode) {
        List<ChatRecord> recordList = nettyMapper.queryChatRecord(userCode);
        //查询群聊信息
        List<ChatRecord> recordGroupList = nettyMapper.queryChatGroupRecord(userCode);
        recordList.addAll(recordGroupList);
        recordList.forEach(v ->{
            v.setShowTime(exchangeMessageTime(v.getMessageTime(),true));
        });
        Map<String,List<ChatRecord>> returnMap = new HashedMap<String,List<ChatRecord>>();
        for (ChatRecord record : recordList) {
            String mappingCode = record.getMappingCode();
            //根据聊天对code拿到聊天信息
            List<ChatRecord> list = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(returnMap.get(mappingCode))){
                list = returnMap.get(mappingCode);
            }
            //加入新的聊天记录
            list.add(record);
            //重新放回去
            returnMap.put(mappingCode,list);
        }
        return returnMap;
    }

    @Override
    public User queryUserInfo(String userCode) {
        return nettyMapper.queryUserInfo(userCode);
    }

    @Override
    public String getWebSocketUrl() {
        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        return String.valueOf(redisUtil.get(Constant.WEB_SOCKET_URL));
    }

    @Override
    public User headPortraitImageUpload(MultipartFile file, String userCode, String nickName){
        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        String headPortraitUrl = String.valueOf(redisUtil.get(Constant.HEAD_PORTRAIT_URL));
        String fileName = file.getOriginalFilename();
        String newFileName = CodeUtil.getCode() + fileName.substring(file.getOriginalFilename().lastIndexOf("."));
        File targetFile = new File("/headImage/", newFileName);
        if(!targetFile.getParentFile().exists()){    //注意，判断父级路径是否存在
            targetFile.getParentFile().mkdirs();
        }

        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),targetFile);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传失败！");
        }
        String headPortrait = "/headImage/" + newFileName;
        //修改头像和昵称
        User user = new User(userCode,nickName,headPortrait);
        nettyMapper.updateHeadPortraitAndNickName(user);

        user.setHeadPortrait(headPortraitUrl + headPortrait);
        return user;
    }

    @Override
    public List<UserFriendVo> queryAddFriendRequestList(String userCode) {
        return nettyMapper.queryAddFriendRequestList(userCode);
    }

    @Override
    @Transactional
    public void agreeAddFriend(UserFriend userFriend) {
        //插入好友信息
        userFriend.setIsFriend(1);
        nettyMapper.addFriend(userFriend);

        //更新是否好友标识
        String userCode = userFriend.getUserCode();
        String friendCode = userFriend.getFriendCode();

        UserFriend dto = new UserFriend(friendCode,userCode,1);
        nettyMapper.updateUserFriend(dto);
    }

    @Override
    @Transactional
    public void addGroupChat(List<UserFriend> list) {
        Set<String> userCodes = new TreeSet<>();
        StringBuilder groupName = new StringBuilder();
        list.forEach(v->{
            userCodes.add(v.getUserCode());
            userCodes.add(v.getFriendCode());
        });

        //插入群聊用户表
        String groupCode = CodeUtil.getCode();
        String mappingCode = CodeUtil.getCode();
        nettyMapper.addGroupChat(groupCode,userCodes,mappingCode);
        //插入群聊信息表
        nettyMapper.insertGroupInfo(groupCode,"群聊");
    }

    @Override
    public List<String> queryGroupChatUsers(String toCode) {
        return nettyMapper.queryGroupChatUsers(toCode);
    }

    @Override
    public List<UserFriendVo> getFriendList(String userCode) {
        List<UserFriendVo> list = nettyMapper.getUserFriendsList(userCode);
        return list;
    }
}
